<template>
  <basic-container>
    <el-container>
      <el-aside width="200px">
        <deptTree ref="building_tree" @treeNode-click="treeNodeClick"></deptTree>
      </el-aside>
      <el-main id="el-main">
        <div class="app-container calendar-list-container" height="600px">
          <!--工具条-->
          <div name="searchColums">
            <el-form :inline="true" :model="filters" size="small" ref="filters" class="searchForm">
              <el-form-item class="el-form-item" label="园区名称" prop="name">
                <el-input class="filter-item" placeholder="园区名称" v-model="filters.name"></el-input>
              </el-form-item>
              <span class="bth_search">
                <el-form-item>
                  <el-button type="success" icon="el-icon-search" v-on:click="getDataGrid(true)">查询</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-refresh" @click="resetSearchForm('filters')">重置</el-button>
                </el-form-item>
              </span>
            </el-form>
          </div>
          <!--toolbar-->
          <el-row id="toolbar_unit">
            <el-col :span="24">
              <div class="grid-content bg-purple-light">
                <el-button type="success" size="mini" icon="el-icon-check" @click="handleAdd" :disabled="addDisabled">新增</el-button>
              </div>
            </el-col>
          </el-row>

          <!--列表-->
          <el-table height="400px" :data="gridDatas" id="dataGrid" empty-text=" " border stripe size="mini" :header-row-class-name="headStyle" highlight-current-row v-loading="listLoading" :row-class-name="tableRowClassName" @sort-change="handleSortChange" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column prop="index" :formatter="index_formatter" label="序号" width="60"></el-table-column>
            <el-table-column prop="name" label="单位名称" min-width="160" show-overflow-tooltip></el-table-column>
            <el-table-column prop="registeredCapital" v-if="isDanwei" label="注册资金(万)" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="companyScop" v-if="isDanwei" label="企业规模" show-overflow-tooltip></el-table-column>
            <el-table-column prop="companyType" v-if="false" show-overflow-tooltip></el-table-column>
            <el-table-column prop="companyTypeName" v-if="isDanwei" label="企业性质" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="manageRange" v-if="false" show-overflow-tooltip></el-table-column>
            <el-table-column prop="manageRangeName" v-if="isDanwei" label="经营范围" show-overflow-tooltip></el-table-column>
            <el-table-column prop="deptProperty" v-if="false" show-overflow-tooltip></el-table-column>
            <el-table-column prop="deptPropertyName" label="类别" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="parentId" v-if="false" show-overflow-tooltip></el-table-column>
            <el-table-column prop="parentName" label="上级组织" width="140" show-overflow-tooltip></el-table-column>
            <el-table-column prop="makeTime" v-if="isDanwei" label="成立日期" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column prop="buildingName" v-if="isDanwei" label="所属楼宇" show-overflow-tooltip></el-table-column>-->
            <el-table-column prop="houseName" label="详细地址" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column prop="buildingId" v-if="false" show-overflow-tooltip></el-table-column>
          <el-table-column prop="houseId" v-if="false" show-overflow-tooltip></el-table-column> -->
            <el-table-column label="操作" width="160" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--工具条-->
          <el-col :span="24" class="toolbar" id="pageDiv">
            <el-pagination small background :current-page="page" @current-change="handleCurrentChange" @size-change="handleSizeChange" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" layout="total,sizes, prev, pager, next" style="float:right;"></el-pagination>
          </el-col>
          <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleAddBeforeClose" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" size="mini" ref="form" label-width="100px">
              <el-input v-model="form.deptId" type="hidden" style="display: none!important;"></el-input>
              <el-input v-model="form.parentId" type="hidden" style="display: none!important;"></el-input>
              <el-input v-model="form.companyId" type="hidden" style="display: none!important;"></el-input>
              <el-col :span="12">

                <el-form-item label="单位名称" v-if="isDanwei" prop="name">
                  <el-input v-model="form.name" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="部门名称" v-else prop="name">
                  <el-input v-model="form.name" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei">
                <el-form-item label="注册资金" placeholder="请输入" prop="registeredCapital">
                  <el-input v-model="form.registeredCapital">
                    <template slot="append">万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei">
                <el-form-item label="企业法人" placeholder="请输入" prop="companyOwner">
                  <el-input v-model="form.companyOwner"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei">
                <el-form-item label="公司规模" prop="companyScop">
                  <el-input v-model="form.companyScop" placeholder="公司规模"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei">
                <el-form-item label="办公租赁面积" prop="companyLeaseSize">
                  <el-input v-model="form.companyLeaseSize" placeholder="办公租赁面积">
                    <template slot="append">平方米</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei">
                <el-form-item label="办公自有面积" prop="companyOwnSize">
                  <el-input v-model="form.companyOwnSize" placeholder="办公自有面积">
                    <template slot="append">平方米</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="类别" prop="deptProperty">
                  <el-select class="filter-item" v-model="form.deptProperty" disabled placeholder="请选择">
                    <el-option v-for="item in deptPropertyOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei">
                <el-form-item label="公司性质" prop="companyType">
                  <el-select class="filter-item" v-model="form.companyType" placeholder="请选择">
                    <el-option v-for="item in companyTypeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei" prop="makeTime">
                <el-form-item label="成立时间">
                  <el-date-picker type="date" placeholder="成立时间" v-model="form.makeTime"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei" prop="employeeNumber">
                <el-form-item label="员工总数">
                  <el-input-number placeholder="员工总数" v-model="form.employeeNumber" disabled></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isDanwei" prop="socialSecurityNumber">
                <el-form-item label="社保人数">
                  <el-input-number placeholder="社保人数" v-model="form.socialSecurityNumber" disabled></el-input-number>
                </el-form-item>
              </el-col>

              <!-- <el-col :span="12" v-if="isDanwei">
              <el-form-item label="所属楼宇" prop="buildingId">
                <el-select class="filter-item" v-model="form.buildingId" placeholder="请选择" @change="handleSelectUnit">
                  <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
              <el-col :span="12" v-if="isDanwei">
                <el-form-item label="主营行业" prop="manageRange">
                  <el-select class="filter-item" v-model="form.manageRange" placeholder="请选择">
                    <el-option v-for="item in manageOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="isDanwei">
                <el-form-item label="详细地址" prop="address">
                  <el-input type="textarea" v-model="form.address" placeholder="详细地址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="isDanwei">
                <el-form-item label="企业简介" prop="profiles">
                  <avue-ueditor v-model="form.profiles"></avue-ueditor>
                </el-form-item>
              </el-col>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel('form')">取 消</el-button>
              <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
              <el-button v-else type="primary" @click="update('form')">修 改</el-button>
            </div>
          </el-dialog>
        </div>
      </el-main>
    </el-container>
  </basic-container>
</template>

<script>
import request from '@/router/axios'
import { mapGetters } from 'vuex'
import deptTree from '../dept/deptTree.vue'
import {
  fetchList,
  fetchTree,
  getObj,
  addObj,
  delObj,
  putObj
} from '@/api/dept'

export default {
  name: 'table_dept',
  components: {
    deptTree
  },
  data() {
    return {
      gridDatas: [],
      filters: {
        liftUserName: '',
        startTimeBegin: '',
        startTimeEnd: '',
        status: ''
      },
      sort: {
        sort: 'sort',
        order: 'asc'
      },
      companyTypeOptions: [],
      deptPropertyOptions: [],
      manageOptions: [],
      total: 0,
      page: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],
      listLoading: false,
      dialogStatus: false,
      isDanwei: true,
      dialogFormVisible: false,
      addDisabled: true,
      btn_add_flag: false,
      form: {
        buildingId: undefined,
        houseId: undefined,
        name: undefined,
        registeredCapital: undefined,
        companyOwner: undefined,
        companyScop: undefined,
        companyLeaseSize: undefined,
        companyOwnSize: undefined,
        deptProperty: undefined,
        makeTime: undefined,
        socialSecurityNumber: undefined,
        manageRange: undefined,
        employeeNumber: undefined,
        address: undefined
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        roleName: [
          {
            required: true,
            message: '角色名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        roleCode: [
          {
            required: true,
            message: '角色编码',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.initDictsData()
    if (this.permissions['sys_dept_add']) {
      this.btn_add_flag = true
    }
  },
  computed: {
    ...mapGetters(['elements', 'permissions'])
  },
  methods: {
    initDictsData: function() {
      request.get('/admin/dict/type/company_type').then(res => {
        if (res.status === 200) {
          this.companyTypeOptions = res.data
        }
      })
      request.get('/admin/dict/type/dept_property').then(res => {
        if (res.status === 200) {
          this.deptPropertyOptions = res.data
        }
      })
      request.get('/admin/dict/type/dept_scop').then(res => {
        if (res.status === 200) {
          this.manageOptions = res.data
        }
      })
    },
    handleSortChange(sort) {
      this.sort = {
        sort: sort.prop,
        order: sort.order == 'ascending' ? 'asc' : 'desc'
      }
      this.getDataGrid()
    },
    tableRowClassName(row, index) {
      //把每一行的索引放进row
      row.index = row.rowIndex
    },
    headStyle({ row, rowIndex }) {
      return 'table_head_style'
    },
    index_formatter: function(row, column, cellValue, index) {
      //放回索引值
      return this.pageSize * (this.page - 1) + 1 + index
    },
    handleCurrentChange(val) {
      this.page = val
      this.getDataGrid()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.getDataGrid()
    },
    resetSearchForm(formName) {
      this.$refs.filters.resetFields()
    },
    selsChange: function(sels) {
      this.sels = sels
    },
    getDataGrid(flag) {
      this.listLoading = true
      // 获取当前树节点选中小区
      var data = this.$refs.building_tree.$refs.tree.getCurrentNode()
      //获取当前树节点选中小区
      if (flag) {
        this.page = 1
      }
      var buildingId = this.treeId
      let para = {
        params: {
          page: this.page,
          limit: this.pageSize,
          name: this.filters.name,
          parentId: data.id,
          companyId: data.companyId,
          deptProperty: data.type
        }
      }
      this.listLoading = true
      request.get('/admin/dept/page', para).then(res => {
        this.total = res.data.total
        var datas = res.data.records
        this.gridDatas = datas
        this.listLoading = false
      })
    },

    handleAdd() {
      this.resetTemp()
      // 获取当前树节点选中小区
      var data = this.$refs.building_tree.$refs.tree.getCurrentNode()
      var node = this.$refs.building_tree.$refs.tree.getNode(data.id)
      this.form.parentId = data.id
      if (node.level == 1) {
        this.isDanwei = true
        this.form.deptProperty = '1'
      } else {
        this.isDanwei = false
        this.form.deptProperty = '2'
        this.form.companyId = data.companyId
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleEdit(index, row) {
      this.dialogFormVisible = true
      this.dialogStatus = 'update'
      this.form = Object.assign({}, row)
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response.data
        this.dialogDeptVisible = true
      })
    },
    handleAddBeforeClose() {
      this.$refs.form.resetFields()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getNodeData(data) {
      this.dialogDeptVisible = false
      this.form.roleDeptId = data.id
      this.form.deptName = data.name
      console.log(data)
    },
    handleDel(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        delObj(row.deptId).then(response => {
          this.dialogFormVisible = false
          this.getDataGrid()
          this.reloadCurrentTreeData()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    create(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(res => {
            if (!res.data) {
              this.$notify({
                title: '添加失败',
                message: '添加失败',
                type: 'faile',
                duration: 2000
              })
              return false
            }
            this.dialogFormVisible = false
            this.getDataGrid()
            this.reloadCurrentTreeData()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          putObj(this.form).then(res => {
            if (!(res.status == 200)) {
              this.$notify({
                title: '修改失败',
                message: '修改失败',
                type: 'faile',
                duration: 2000
              })
              return false
            }
            this.dialogFormVisible = false
            this.getDataGrid()
            this.reloadCurrentTreeData()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    resetTemp() {
      this.form = {
        id: undefined,
        roleName: undefined,
        roleCode: undefined,
        roleDesc: undefined,
        communityId: undefined,
        buildingId: undefined,
        unitId: undefined
      }
    },
    reloadCurrentTreeData() {
      var data = this.$refs.building_tree.$refs.tree.getCurrentNode()
      var node = this.$refs.building_tree.$refs.tree.getNode(data.id)
      let para = {
        params: {
          parentId: data.id
        }
      }
      //加载企业节点
      request.get('/admin/dept/getDeptNodeByParent', para).then(res => {
        if (res.status === 200) {
          this.$refs.building_tree.$refs.tree.updateKeyChildren(
            node.key,
            res.data
          )
        }
      })
    },
    handleSelectUnit() {},
    treeNodeClick(data, node) {
      //sys_park_add 是否可以新增企业
      //sys_dept_add 时刻可以新增部门
      //烂代码改烂代码  不改了
      if (node.level === 1) {
        if (this.permissions['sys_park_add']) {
          this.btn_add_flag = true
        } else {
          this.btn_add_flag = false
        }
        this.isDanwei = true
      } else {
        this.isDanwei = false
        if (this.permissions['sys_dept_add']) {
          this.btn_add_flag = true
        }
      }
      if (this.btn_add_flag) {
        this.addDisabled = false
      } else {
        this.addDisabled = true
      }
      this.getDataGrid(true)
    }
  }
}
</script>
